import requests
import sys
import github
repos = []
def search_github_repos(query, per_page=100):
    """
    使用 GitHub API 搜索仓库
    :param query: 搜索关键词
    :param per_page: 返回结果数量（最多100）
    """
    url = "https://api.github.com/search/repositories"
    headers = {
        "Accept": "application/vnd.github.v3+json"
    }
    params = {
        "q": query,
        "sort": "stars",
        "order": "desc",
        "per_page": min(per_page, 100)  # GitHub 最多返回100条
    }

    try:
        response = requests.get(url, headers=headers, params=params)
        response.raise_for_status()  # 检查 HTTP 错误
        data = response.json()

        if data.get("total_count", 0) == 0:
            print("没有找到相关仓库。")
            return

        print(f"\n找到 {data['total_count']} 个仓库，显示前 {len(data['items'])} 个：\n")
        i = 1
        for repo in data["items"]:
            name = repo["full_name"]
            url = repo["html_url"]
            description = repo["description"] or "无描述"
            stars = repo["stargazers_count"]
            repos.append(name)
            print(f"{str(i)} | 🌟 {stars} | {name}")
            print(f"   地址: {url}")
            print(description[:100])
            i = i+1
    
    except requests.exceptions.HTTPError as e:
        if response.status_code == 403:
            print("⚠️ 请求受限（可能达到速率限制）。建议设置 GitHub Token。")
        else:
            print(f"HTTP 错误: {e}")
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
    except KeyError as e:
        print(f"解析响应失败: 缺少字段 {e}")

def main():
    if len(sys.argv) < 2:
        print("用法: python github_search.py <搜索关键词>")
        sys.exit(1)

    query = " ".join(sys.argv[1:])
    print(f"正在搜索 GitHub 仓库: '{query}'")
    search_github_repos(query, per_page=100)
    while True:
        choice = int(input("请选择仓库"))
        import os
        github.main(repos[choice-1])

if __name__ == "__main__":
    main()
